package model

import (
	"gin/database"
	"github.com/Gre-Z/common/jtime"
	teamones_helper "github.com/teamones-open/go-helper"
	"strings"
)

type Log struct {
	Created jtime.TstampTime `json:"created" gorm:"column:created"`
	Uuid    string           `json:"uuid" gorm:"column:uuid"`
}

// 设置表名
func (Log) TableName() string {
	return "log"
}

func (this *Log) Insert() (id int64, err error) {
	result := Mysql.DB.Create(&this)
	id = this.Id
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

func (this *Log) Find(Param teamones_helper.SelectQueryParam) (resData Log, err error) {

	logOne := new(Log)
	db := Mysql.DB

	// 组装过滤条件
	if Param.Where != nil {
		for key, val := range Param.Where {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	// 应用分页
	db = db.Select(Param.Fields)

	result := db.First(&logOne)
	if result.Error != nil {
		err = result.Error
		return
	}

	return *logOne, err
}

func (this *Log) Select(Param teamones_helper.SelectQueryParam) (total int, resData []Log, err error) {

	logs := make([]Log, 0)
	db := Mysql.DB

	// 组装过滤条件
	if Param.Where != nil {
		for key, val := range Param.Where {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	// 获取总条数
	db.Model(&Log{}).Count(&total)

	// 查找所有数据

	// 应用分页
	db = db.Select(Param.Fields).Limit(Param.Limit).Offset(Param.Offset)

	// 应用排序参数
	if Param.Order != "" {
		db = db.Order(Param.Order)
	}

	result := db.Find(&logs)
	if result.Error != nil {
		err = result.Error
		return
	}

	return total, logs, err
}
